package com.lvtu.monitor.module.web.config;


import com.alibaba.fastjson.JSON;
import com.lvmama.com.lvtu.common.utils.MemcachedUtil;
import com.lvmama.com.lvtu.common.utils.StringUtil;
import com.lvtu.monitor.dao.config.MemConfig;
import com.lvtu.monitor.module.web.module.ResultHandler;
import com.lvtu.monitor.mongo.service.IBaseMongoService;
import com.lvtu.monitor.shiro.UserUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: ConfigAction.java
 * @Package com.lvtu.monitor.module.web.config
 * @Description: TODO
 * @author dengcheng
 * @date 2015-6-8 上午11:52:24
 * @version V1.0.0
 */
@Controller  // 在类上面定义，表明该类为控制器，返回字符串与redirect:xxx
@RequestMapping("/switch")
public class SwitchConfigAction {

	private final static Logger logger = Logger
			.getLogger(SwitchConfigAction.class);
	@Autowired
	IBaseMongoService mongoService;


	@RequestMapping("/toSwitchConfig")
	public String toSwitchConfig(){

		return "switch/sw_list";
	}

	@RequestMapping("/activeMemConfig")
	@ResponseBody
	public boolean activeMemConfig(String id, String enable){

		MemConfig mem = mongoService.findOne(id, MemConfig.class);
		mem.setEnable(enable);
        Map<String, Object> updateMap = new HashMap<String, Object>();
        updateMap.put("enable", enable);
		try {
			mongoService.updateOne(id, updateMap, MemConfig.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if ("true".equals(enable)) {
			logger.info(String.format("Operator [%s]:switch activated...key:%s,value:%s.",
                    UserUtils.getUserName(), mem.getMemKey(), mem.getValue()));
			MemcachedUtil.getInstance().addOrIncrAndInit(mem.getMemKey(), mem.getValue());
		} else {
			logger.info(String.format("Operator [%s]:switch deactivated...key:%s,value:%s.",
                    UserUtils.getUserName(), mem.getMemKey(), mem.getValue()));
			MemcachedUtil.getInstance().remove(mem.getMemKey());
		}
		return true;
	}

	@RequestMapping("/addSwitch")
	@ResponseBody
	public boolean AddConfigKey(MemConfig mem,String _id){

		if("true".equals(mem.getEnable())){
			MemcachedUtil.getInstance().addOrIncrAndInit(mem.getMemKey(), mem.getValue());
		}
		if(StringUtil.isNotEmptyString(_id)){

			try {
				String id = mem.get_id();
                Map<String, Object> updateMap = new HashMap<String, Object>();
                updateMap.put("value", mem.getValue());
                updateMap.put("memValue", mem.getMemValue());
                updateMap.put("enable", mem.getEnable());
                updateMap.put("memKey", mem.getMemKey());
                updateMap.put("title", mem.getTitle());
                updateMap.put("type", mem.getType());
				mongoService.updateOne(_id, updateMap, MemConfig.class);
				logger.info(String.format("Operator [%s]:switch updated...%s",
                        UserUtils.getUserName(), updateMap));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			mongoService.insert(mem);
			logger.info(String.format("Operator [%s]:switch inserted...%s",
                    UserUtils.getUserName(), JSON.toJSONString(mem)));
		}

		return true;
	}

	@RequestMapping("/loadAllMemeKeys")
	@ResponseBody
	public ResultHandler loadAllMemeKeys(){
		List<MemConfig> result = mongoService.findAll(MemConfig.class);
		for (MemConfig memConfig : result) {
            long memValue = MemcachedUtil.getInstance().getCounter(memConfig.getMemKey());
            memConfig.setMemValue(memValue);
		}
		ResultHandler list = new ResultHandler();
		list.setRows(result);
		return list;
	}

	@RequestMapping("/deleteMemConfig")
	@ResponseBody
	public boolean deleteMemConfig(String id){
		MemConfig mem = mongoService.findOne(id, MemConfig.class);
		MemcachedUtil.getInstance().remove(mem.getMemKey());
		mongoService.removeOne(id, MemConfig.class);

		logger.info(String.format("Operator [%s]:switch deleted...key:%s",
                UserUtils.getUserName(), mem.getMemKey()));
		return true;
	}
}
